﻿using itemApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace itemApi.Controllers
{
    public class menuController : ApiController
    {
        [HttpPost]
        public IHttpActionResult getmenulist([FromBody] Users use)
        {
            using (crmEntities db = new crmEntities())
            {
                //获取登录用户Id
                Users userId = db.Users.SingleOrDefault(p => p.uid == use.uid);
                //根据用户id获取对应用户角色Id
                var rolesId_list = db.UserRoles.Where(p => p.UserId == userId.uid).ToList();
                var list1 = rolesId_list.Select(p => new
                {
                    RoleId = p.RoleId
                }).ToList();
                //用角色id去获得对应模块id
                List<Modules> data1 = new List<Modules>();
                List<Modules> data2 = new List<Modules>();
                foreach (var item in list1)
                {
                    var moduleId_list = db.RoleModules.Where(p => p.RoleId == item.RoleId).ToList();
                    var list2 = moduleId_list.AsEnumerable();

                    foreach (var itema in list2)
                    {
                        var list3 = db.Modules.FirstOrDefault(p => p.Id == itema.ModuleId);
                        if (list3.ParentId == 0)
                        {
                            data1.Add(list3);
                        }
                        else
                        {
                            data2.Add(list3);
                        }
                    }
                    //获取父级模块
                }
                var list5 = data1.Select(p => new
                {
                    Id = p.Id,
                    Name = p.Name,
                    ParentId = p.ParentId,
                    Path = p.Path,
                    Weight = p.Weight
                }).ToList().Distinct();
                var list6 = data2.Select(p => new
                {
                    Id = p.Id,
                    Name = p.Name,
                    ParentId = p.ParentId,
                    Path = p.Path,
                    Weight = p.Weight
                }).ToList().Distinct();
                return Json(new { code = 0, data1 = list5, data2 = list6, msg = "请求成功！",username=userId.loginName });
            }
        }
    }
}